package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.ApUserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 保存点赞行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {

        //检查参数
        if (null == dto || null == dto.getArticleId() || dto.getType() > 2
                || dto.getType() < 0 || dto.getOperation() != 0 || dto.getOperation() != 1) {
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //查询当前用户
        Integer userId = ApUserThreadLocal.getUserId();
        if (null == userId || userId == 0) {
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        if (null == apBehaviorEntry) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询点赞数据是否存在
        ApLikesBehavior apLikesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId()));
        if (null == apLikesBehavior) {

            //没有数据  添加数据
            apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setEntryId(apBehaviorEntry.getId());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setType(dto.getType());

            apLikesBehavior.setCreatedTime(new Date());

            save(apLikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //有数据 修改数据
        apLikesBehavior.setOperation(dto.getOperation() );
        apLikesBehavior.setCreatedTime(new Date());

        //修改数据
        updateById(apLikesBehavior);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
